
const Dict = {
    city: [
        { name: 'City1', value: '01' },
        { name: 'City2', value: '02' },
    ]
}

const DictMapping = {};
const DictQueueCache = {};
const DictQueueEvent = async function (type) {
    return await Common.GetDict({ type })
};

async function GetDict(type) {
    if (type && Dict[type]) {
        return JSON.parse(JSON.stringify(Dict[type]))
    } else if (type && !Dict[type]) {
        if (DictQueueCache[type]) {
            return DictQueueCache[type]
        } else {
            const _event = DictQueueEvent(type);
            DictQueueCache[type] = _event;
            try {
                const res = await _event;
                Dict[type] = res;
                delete DictQueueCache[type];
                return res;
            } catch (error) {
                delete DictQueueCache[type]
                throw error;
            }
        }
    }
}


async function FormatDictToMapping(options) {
    const type = options.type;
    const key = options.key || 'value';
    try {
        let res = await GetDict(type);
        const _data = {};
        res.forEach(item => {
            _data[item[key]] = item;
        })
        return _data;
    } catch (error) {
        console.error('格式化失败 =>', type, error)
    }
}

export default async function (el, binding, vnode) {
    const type = binding.arg;
    const options = binding.value;
    let value, valueKey, showKey;
    if (Array.isArray(options)) {
        value = options[0];
        valueKey = options[1] || 'value';
        showKey = options[2] || 'label';
    } else {
        value = options;
        valueKey = 'value';
        showKey = 'label';
    };

    let _dict = DictMapping[`${type}_${valueKey}_${showKey}`];
    if (!_dist) {
        _dict = DictMapping[`${type}_${valueKey}_${showKey}`] = await FormatDictToMapping({ type, key: valueKey });
    };

    if (_dict[value] && Object.prototype.hasOwnProperty.call(_dict[value], showKey)) {
        el.innerHtml = _dict[value][showKey]
    } else {
        el.innerHtml = value;
    }

}

export { GetDict };